package com.yfp.client.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.yfp.client.domain.*;
import com.yfp.client.domain.*;
import com.yfp.client.domain.vo.ClientActivityRewardsRankVO;
import com.yfp.client.domain.vo.ClientActivityVO;
import com.yfp.client.domain.vo.ClientIdAndFinishPositionVO;
import com.yfp.client.domain.vo.CountClientActivityVO;
import com.yfp.client.mapper.*;
import com.yfp.client.mapper.*;
import com.yfp.client.service.ClientActivityService;
import com.yfp.client.service.ClientService;
import com.yfp.client.util.SecurityUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description: 客户活动
 * 
 * @CreateDate: 2024/7/19 13:54
 * @UpdateUser: 
 * @UpdateDate: 2024/7/19 13:54
 * @UpdateRemark: 暂无修改
 * @Version: 1.0
 */
@Service
@Slf4j
public class ClientActivityServiceImpl implements ClientActivityService {
    @Autowired
    private MarActivityClientMapper marActivityClientMapper;
    @Autowired
    private MarCouponMapper marCouponMapper;
    @Autowired
    private MarActivityMapper marActivityMapper;
    @Autowired
    private MarketingMapper marketingMapper;
    @Resource
    private ClientService clientService;
    @Resource
    private OrderListMapper orderListMapper;
    @Resource
    private MarActivityPositionMapper marActivityPositionMapper;

    @Override
    public CountClientActivityVO countClientActivityByMarketingIdAndClientId(Long marketingId, String clientId) {
        return marActivityClientMapper.countClientActivityByMarketingIdAndClientId(marketingId, clientId);
    }

    @Override
    public List<ClientActivityVO> findByMarketingIdAndClientId(Long marketingId, String clientId) {
        return marActivityClientMapper.findByMarketingIdAndClientId(marketingId, clientId);
    }

    @Override
    public MarActivity findMarActivityById(Long id) {
        return marActivityMapper.findById(id);
    }

    @Override
    public MarCoupon findMarCouponById(Long id) {
        return marCouponMapper.findById(id);
    }

    @Override
    public Marketing findMarketingById(Long id) {
        return marketingMapper.findById(id);
    }

    @Override
    public MarActivity findValidByType(Integer type,String cityName) {

        ClientIdAndFinishPositionVO positionVO = orderListMapper.selectClientIdAndFinishPositionId(SecurityUtils.getClientId());

        log.info("订单点位:{}",positionVO);
        if (!BeanUtil.isEmpty(positionVO)) {
            // 查询顺序   特殊指定-》特殊全部-》普通指定-》普通全部  存在则直接返回
            // 特殊指定
            MarActivity marActivity1 = marActivityPositionMapper.getByPositionIdAndLabel(positionVO.getPositionId(),4);
            if (!BeanUtil.isEmpty(marActivity1) && (marActivity1.getStatus() == 1 || marActivity1.getStatus() == 4)) {
                return marActivity1;
            }
            // 普通指定
            MarActivity marActivity3 = marActivityPositionMapper.getByPositionIdAndLabel(positionVO.getPositionId(),2);
            if (!BeanUtil.isEmpty(marActivity3) && (marActivity3.getStatus() == 1 || marActivity3.getStatus() == 4)) {
                return marActivity3;
            }
            // 点位类型
            MarActivity marActivity2 = null;
            switch (positionVO.getType()){
                case 1:
                    // 特殊全部
                    marActivity2 = marActivityPositionMapper.getAllPositionIdAndLabel(1,3,cityName);
                    break;
                case 2:
                    //普通全部
                    marActivity2 = marActivityPositionMapper.getAllPositionIdAndLabel(1,1,cityName);
                    break;
            }

            return marActivity2;
        } else {
            // 没有订单默认普通全部
            MarActivity marActivity4 = marActivityPositionMapper.getAllPositionIdAndLabel(1,1,cityName);
            return marActivity4;
        }
    }

    @Override
    public List<ClientActivityRewardsRankVO> getRewardsRank(Long marketingId) {

        List<MarActivityClient> marActivityClients = marActivityClientMapper.getRewardsRank(marketingId);

        List<String> clientIdList = marActivityClients.stream().map(MarActivityClient::getHostClientId).distinct().collect(Collectors.toList());
        Map<String, Client> clientMapById = clientService.getByIds(clientIdList).stream().collect(Collectors.toMap(Client::getId, Function.identity()));

        // 统计主-客户ID邀请总数，如果数量相同按照创建时间排序
        List<ClientActivityRewardsRankVO> clientActivityRewardsRankVOList = marActivityClients.stream().collect(Collectors.groupingBy(MarActivityClient::getHostClientId)).entrySet().stream().map(item -> {
            String hostClientId = item.getKey();
            // 统计集合的数量
            long count = item.getValue().stream().count();
            // 获取集合最近的日期
            Date createTime = item.getValue().stream().max(Comparator.comparing(MarActivityClient::getCreateTime)).get().getCreateTime();
            Client client = clientMapById.getOrDefault(hostClientId, new Client());
            ClientActivityRewardsRankVO clientActivityRewardsRankVO = new ClientActivityRewardsRankVO();
            clientActivityRewardsRankVO.setClientId(hostClientId);
            clientActivityRewardsRankVO.setTotalCount(count);
            clientActivityRewardsRankVO.setNickName(client.getNickName());
            clientActivityRewardsRankVO.setAvatar(client.getHeadImg());
            clientActivityRewardsRankVO.setCreateTime(createTime);
            return clientActivityRewardsRankVO;
        }).sorted(Comparator.comparing(ClientActivityRewardsRankVO::getTotalCount, Comparator.reverseOrder()).thenComparing(ClientActivityRewardsRankVO::getCreateTime, Comparator.naturalOrder())).collect(Collectors.toList());

        return clientActivityRewardsRankVOList;
    }
}